package com.graduation.check.controller;

import com.github.pagehelper.PageInfo;
import com.graduation.check.dto.TitleCheckRequest;
import com.graduation.check.dto.TitleCheckResponse;
import com.graduation.check.dto.TitleCheckHistoryResponse;
import com.graduation.check.service.TitleCheckService;
import com.graduation.check.utils.ApiResponse;
import com.graduation.check.entity.User;
import com.graduation.check.mapper.UserMapper;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/student/title-check")  // context-path=/api已在application.properties配置
public class StudentTitleCheckController {

    @Autowired
    private TitleCheckService titleCheckService;

    @Autowired
    private UserMapper userMapper;

    /**
     * 提交题目查重
     */
    @PostMapping
    public ApiResponse<TitleCheckResponse> submitTitleCheck(
            @Valid @RequestBody TitleCheckRequest request,
            Authentication authentication) {
        try {
            log.info("收到题目查重请求 - 题目: {}, 范围: {}, 年份: {}",
                    request.getTitle(), request.getCheckScope(), request.getYearRange());

            Long studentId = getCurrentStudentId(authentication);
            log.info("用户认证成功 - 学生ID: {}", studentId);

            TitleCheckResponse response = titleCheckService.submitTitleCheck(request, studentId);
            return ApiResponse.success("题目查重完成", response);
        } catch (Exception e) {
            log.error("题目查重处理失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }

    /**
     * 获取题目查重历史
     */
    @GetMapping("/history")
    public ApiResponse<PageInfo<TitleCheckHistoryResponse>> getTitleCheckHistory(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            Authentication authentication) {
        try {
            log.info("获取查重历史 - 页码: {}, 大小: {}", page, size);

            Long studentId = getCurrentStudentId(authentication);

            // 首先尝试使用PageHelper分页
            PageInfo<TitleCheckHistoryResponse> history = titleCheckService.getCheckHistory(studentId, page, size);

            // 如果PageHelper返回空数据，尝试使用手动分页
            if (history == null || history.getList() == null || history.getList().isEmpty()) {
                log.warn("PageHelper分页返回空数据，尝试使用手动分页");
                history = titleCheckService.getCheckHistoryManual(studentId, page, size);
            }

            log.info("成功返回历史记录 - 总数: {}, 当前页记录数: {}",
                    history.getTotal(), history.getList().size());
            return ApiResponse.success(history);
        } catch (Exception e) {
            log.error("获取查重历史失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }

    /**
     * 获取查重结果详情
     */
    @GetMapping("/{taskId}")
    public ApiResponse<TitleCheckResponse> getCheckResult(
            @PathVariable Long taskId,
            Authentication authentication) {
        try {
            log.info("获取查重结果详情 - 任务ID: {}", taskId);

            Long studentId = getCurrentStudentId(authentication);
            TitleCheckResponse response = titleCheckService.getCheckResult(taskId, studentId);

            return ApiResponse.success(response);
        } catch (Exception e) {
            log.error("获取查重结果详情失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }

    /**
     * 从认证信息中获取学生ID
     */
    private Long getCurrentStudentId(Authentication authentication) {
        if (authentication != null && authentication.isAuthenticated()) {
            String username = authentication.getName();
            log.debug("获取当前用户 - 用户名: {}", username);

            User user = userMapper.findByAccount(username);
            if (user == null) {
                throw new RuntimeException("用户不存在: " + username);
            }

            log.debug("用户信息获取成功 - 用户ID: {}, 角色: {}", user.getId(), user.getUserType());
            return user.getId();
        }
        throw new RuntimeException("用户未认证");
    }
}